package com.LeetCode.Array;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 两个数组的交集
 */
public class TwoArrayUnionSet {

    public int[] intersect(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        List<Integer> list = new ArrayList<>();
        for(int i = 0, j = 0; i < nums1.length && j < nums2.length; ){
            if(nums1[i] < nums2[j]){
                i++;
            }else if(nums1[i] > nums2[j]){
                j++;
            }else{
                list.add(nums1[i]);
                i++;
                j++;
            }
        }

        int[] res = new int[list.size()];
        for(int i = 0; i<list.size(); i++){
            res[i] = list.get(i);
        }

        return res;
    }

    @Test
    public void test(){
        int[] arr1 = {4,9,5};
        int[] arr2 = {9,4,9,8,5};
        for(int i : intersect(arr1,arr2)){
            System.out.print(i+" ");
        }
    }
}
